<template>
  <div class="business-listings-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">本地房源</h1>
      <p class="page-subtitle">发现您身边的优质房源</p>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-filter-section">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input v-model="searchQuery" placeholder="搜索房源名称、服务内容..." size="large" clearable @input="handleSearch">
          <template #append>
            <el-icon @click="handleSearch" style="cursor: pointer"><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <!-- 筛选器 -->
      <div class="filters-row">
        <el-select v-model="selectedCategory" placeholder="选择分类" clearable @change="handleFilter" style="width: 150px">
          <el-option label="全部分类" value="" />
          <el-option label="住宅" value="住宅" />
          <el-option label="公寓" value="公寓" />
          <el-option label="写字楼" value="写字楼" />
          <el-option label="厂房" value="厂房" />
          <el-option label="仓库" value="仓库" />
          <el-option label="商铺" value="商铺" />
        </el-select>

        <el-select v-model="sortBy" placeholder="排序方式" @change="handleSort" style="width: 120px">
          <el-option label="综合排序" value="default" />
          <el-option label="面积升序" value="area" />
          <el-option label="售价升序" value="price" />
          <el-option label="最新发布" value="newest" />
        </el-select>
      </div>
    </div>

    <!-- 房源卡片网格 -->
    <div class="business-grid" v-loading="loading">
      <el-empty v-if="list.length == 0" description="暂无数据" />
      <RouterLink :to="`/house/detail?id=${item.id}`" target="_blank" v-for="(item, index) in list" :key="index">
        <el-card class="business-card" shadow="hover">
          <div class="card-content">
            <!-- 房源图片 -->
            <div class="business-image" v-if="item.image">
              <img :src="item.image" :alt="item.name" />
              <div class="rating-badge">
                <el-icon><Star /></el-icon>
                {{ item.rating }}
              </div>
            </div>

            <!-- 房源信息 -->
            <div class="business-info">
              <h3 class="business-name">{{ item.name }}</h3>
              <p class="business-category">{{ item.category }}</p>
              <p class="business-description">{{ item.description }}</p>

              <div class="business-details">
                <div class="detail-item">
                  <el-icon><Location /></el-icon>
                  <span>{{ item.address }}</span>
                </div>
                <div class="detail-item">
                  <el-icon><Money /></el-icon>
                  <span v-if="item.facePrice">售价： 面议</span>
                  <span v-else>售价：{{ formatPrice(item.price) }}</span>
                </div>
              </div>

              <!-- 服务标签 -->
              <div class="service-tags" v-if="item.tagsJson">
                <el-tag v-for="tag in JSON.parse(item.tagsJson)" :key="tag" size="small" type="info">
                  {{ tag }}
                </el-tag>
              </div>

              <!-- 操作按钮 -->
              <div class="card-actions">
                <el-popconfirm class="box-item" title="你确定删除该数据" @confirm="handleRemove(item)" placement="top">
                  <template #reference>
                    <el-button type="danger" v-if="showAdminOpts" size="small"> 删除 </el-button>
                  </template>
                </el-popconfirm>
                <RouterLink :to="`/house/detail?id=${item.id}`" target="_blank">
                  <el-button type="primary" size="small"> 查看详情 </el-button>
                </RouterLink>
                <el-button size="small" @click="callBusiness(item.phone)">
                  <el-icon><Phone /></el-icon>
                  拨打电话
                </el-button>
              </div>
            </div>
          </div>
        </el-card>
      </RouterLink>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination background layout="prev, pager, next" :page-size="10" :total="totalCount" @change="handleCurrentChange" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive } from 'vue'
import { useHead } from '@vueuse/head'
import { fetchList, remove } from '@/apis/house'
import { Search, Star, Location, Money, Phone } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router'

const userStore = useUserStore()

const router = useRouter()

const showAdminOpts = computed(() => {
  return userStore.showAdminOpts ?? false
})

// 设置页面标题和描述
useHead({
  title: '本地房源 - 发现优质房源',
  meta: [
    { name: 'description', content: '浏览本地房源，发现优质房源。' },
    { name: 'keywords', content: '房源, 买房, 卖房, 出售, 出租' }
  ]
})
const totalCount = ref(100) // 假设总职位数为1000
const searchQuery = ref('') // 搜索关键词
const listQuery = {
  page: 1,
  pageSize: 12,
  keyword: ''
}

const list = reactive<any>([])

const loading = ref(false)
const fetchData = () => {
  // 模拟获取数据
  listQuery.keyword = searchQuery.value.trim()
  loading.value = true
  fetchList(listQuery)
    .then((response) => {
      let { code, result, message } = response.data
      if (code !== 200) {
        throw new Error(message || '获取数据失败')
      }
      if (result.page == 1) {
        list.splice(0, list.length) // 清空列表
      }
      totalCount.value = result.total
      for (let item of result.items) {
        let imgs = []

        if (item.imageUrls) {
          imgs = JSON.parse(item.imageUrls)
        }
        item.image = imgs.length > 0 ? imgs[0] : ''
      }
      list.splice(0, 0, ...result.items)
      // console.log('获取到的数据:', result.items)
    })
    .catch((error) => {
      console.log(error)
      console.error('获取数据失败:', error)
    })
    .finally(() => {
      loading.value = false
    })
}

// 响应式数据

const selectedCategory = ref('')
const sortBy = ref('default')
const currentPage = ref(1)

// 方法
const handleSearch = () => {
  fetchData()
}

const handleFilter = () => {
  currentPage.value = 1
}

const formatPrice = (price: number) => {
  // 检查输入是否为有效数字
  if (typeof price !== 'number' || isNaN(price)) {
    return '无效价格'
  }

  // 如果价格大于等于10000，转换为万元显示
  if (price >= 10000) {
    const wanPrice = price / 10000
    // 保留适当的小数位数
    return wanPrice.toFixed(wanPrice % 1 === 0 ? 0 : 2) + ' 万元'
  } else {
    // 低于10000的价格直接显示为元
    return price.toFixed(0) + ' 元'
  }
}

const handleRemove = (item: any) => {
  // 处理删除逻辑
  remove(item.id)
    .then((response) => {
      let { code, message } = response.data
      if (code !== 200) {
        throw new Error(message || '删除失败')
      }
      // 删除成功后重新获取数据
      fetchData()
    })
    .catch((error) => {
      console.error('删除失败:', error)
    })
}

const handleSort = () => {
  currentPage.value = 1
}

const handleCurrentChange = (val: number, pagesize: number) => {
  listQuery.page = val
  listQuery.pageSize = pagesize
  fetchData()
}

const callBusiness = (phone: string) => {
  window.open(`tel:${phone}`)
}

onMounted(() => {
  // 组件挂载后的初始化操作
  fetchData()
})
</script>

<style scoped>
.business-listings-container {
  max-width: var(--page-max-width);
  background-color: #f8fafc;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-title {
  font-family: 'Space Grotesk', sans-serif;
  font-size: 1.5rem;
  font-weight: bold;
  color: #2563eb;
  margin-bottom: 10px;
}

.page-subtitle {
  font-size: 1.1rem;
  color: #6b7280;
  margin: 0;
}

.search-filter-section {
  background: white;
  padding: 25px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 30px;
}

.search-bar {
  margin-bottom: 20px;
}

.filters-row {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
  align-items: center;
}

.business-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.business-card {
  border-radius: 12px;
  overflow: hidden;
  transition:
    transform 0.2s ease,
    box-shadow 0.2s ease;
}

.business-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.card-content {
  padding: 0;
}

.business-image {
  position: relative;
  height: 180px;
  overflow: hidden;
}

.business-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.rating-badge {
  position: absolute;
  top: 10px;
  right: 10px;
  background: rgba(37, 99, 235, 0.9);
  color: white;
  padding: 4px 8px;
  border-radius: 20px;
  font-size: 0.85rem;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 4px;
}

.business-info {
  padding: 20px;
}

.business-name {
  font-family: 'Space Grotesk', sans-serif;
  font-size: 1.3rem;
  font-weight: bold;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.business-category {
  color: #2563eb;
  font-size: 0.9rem;
  font-weight: 600;
  margin: 0 0 10px 0;
}

.business-description {
  color: #6b7280;
  font-size: 0.95rem;
  line-height: 1.5;
  margin: 0 0 15px 0;

  display: -webkit-box;
  color: #555;
  -webkit-line-clamp: 3; /* 限制2行 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.4;
}

.business-details {
  margin-bottom: 15px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 6px;
  font-size: 0.9rem;
  color: #4b5563;
}

.service-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-bottom: 20px;
}

.card-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .business-grid {
    grid-template-columns: 1fr;
  }

  .filters-row {
    flex-direction: column;
    align-items: stretch;
  }

  .filters-row .el-select {
    width: 100% !important;
  }

  .page-title {
    font-size: 2rem;
  }
}

@media (max-width: 480px) {
  .business-listings-container {
    padding: 15px;
  }

  .search-filter-section {
    padding: 20px;
  }

  .card-actions {
    flex-direction: column;
  }
}
</style>
